package 经典例题;

import java.util.*;

public class 从上到下打印二叉树2 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> lists = new LinkedList<>();
        Queue<TreeNode> q=new LinkedList();
        if (root==null)
            return lists;
        q.offer(root);
        while (!q.isEmpty()){
            List<Integer> list = new LinkedList<>();
            for (int i = q.size(); i>0 ; i--) {
                TreeNode poll = q.poll();
                list.add(poll.val);
                if(poll.left!=null)
                    q.offer(poll.left);
                if (poll.right!=null)
                    q.offer(poll.right);
            }
            lists.add(new ArrayList<>(list));
        }
        Collections.reverse(lists);
        return lists;
    }
}
